package com.sgb.capital.view.ui.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.LinearLayout;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.TimePickerView;
import com.sgb.capital.R;
import com.sgb.capital.base.BaseActivity;
import com.sgb.capital.callback.Constants;
import com.sgb.capital.callback.ZMessageEvent;
import com.sgb.capital.databinding.CapitalActivityBinding;
import com.sgb.capital.model.Bean;
import com.sgb.capital.model.BusinessInfoByCompanyEntity;
import com.sgb.capital.model.CapitalEntity;
import com.sgb.capital.model.PayFlowStatisticsEntity;
import com.sgb.capital.utils.Utils;
import com.sgb.capital.view.pop.TipPop;
import com.sgb.capital.view.ui.adapter.TypeAdapter;
import com.sgb.capital.view.widget.MToast;
import com.sgb.capital.viewmodel.CapitalModel;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;

/**
 * 作者:张磊
 * 日期:2021/2/20 0020
 * 说明:资金中心1.4.0
 */


public class CapitalActivity extends BaseActivity {
    private CapitalModel mModel;
    private CapitalActivityBinding mBinding;
    private boolean isOn = false;
    private TimePickerView mTimePicker;
    private String mBalance = "0.00";
    private String mAssBal = "0.00";
    private TipPop mTip;
    private TipPop mTipBind;
    private TipPop mTipNoOpen;
    private TypeAdapter mAdapter;
    private SimpleDateFormat mTimeStyle;
    private float mPayeeAmount;
    private float mPayAmount;
    private int mProcess;
    private boolean mIsUser;
    private String mMoney = "0.00";


    public static void start(Context context, boolean isUser) {
        Intent intent = new Intent(context, CapitalActivity.class);
        intent.putExtra("isUser", isUser);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        mBinding = DataBindingUtil.setContentView(this, R.layout.capital_activity);
        mIsUser = getIntent().getBooleanExtra("isUser", false);
        mBinding.llBtn.setVisibility(mIsUser ? View.GONE : View.VISIBLE);
        mBinding.tvTitle.setText(mIsUser ? "个人钱包" : "企业钱包");
        mBinding.tvTip1.setText(mIsUser ? "开通个人钱包" : "开通企业钱包");
        mBinding.tvTip1.setTextColor(Utils.getColor(R.color.color_1F2F4E));
    }

    public void initData() {
        mModel = new ViewModelProvider(this).get(CapitalModel.class);
        mBinding.ivEye.setImageResource(isOn ? R.mipmap.eye_on : R.mipmap.eye_off);
        mBinding.tvBalanceMoney.setText(isOn ? mBalance : "*****");
        mBinding.tvRetentionMoney.setText(isOn ? Utils.getDecimalFormat(Float.parseFloat(mAssBal)) : "*****");
        mBinding.tvIncomeMoney.setText(isOn ? mPayeeAmount + "" : "*****");
        mBinding.tvExpendMoney.setText(isOn ? mPayAmount + "" : "*****");
        mBinding.rvType.setLayoutManager(new GridLayoutManager(Utils.getContext(), 3));
        List<Bean> beans = new ArrayList<>();
        beans.add(new Bean(0, "提现"));
        beans.add(new Bean(2, "账务流水"));
        beans.add(new Bean(4, "银行卡管理"));
        beans.add(new Bean(5, "余额充值"));
        beans.add(new Bean(1, "账户明细"));
        //beans.add(new Bean(3, "费用查询"));
        beans.add(new Bean(3, mIsUser ? "费用查询" : "在线转账"));
        if (!mIsUser) {
            beans.add(new Bean(6, "已付账单"));
            beans.add(new Bean(8, "已收账单"));
            beans.add(new Bean(7, "退款列表"));
        }
        mAdapter = new TypeAdapter(beans);
        mBinding.rvType.setAdapter(mAdapter);
        // 初始化弹框
        mTipBind = new TipPop(this, "温馨提示", "暂未绑定提现银行卡，请及时绑定", "立即绑卡", "知道了");
        mTip = new TipPop(this, "温馨提示", "交易完成后，可解冻对应金额", null, "知道了");
        mTipNoOpen = new TipPop(this, "温馨提示", "开通在线收款账户后\n" +
                "可使用此功能", "前往开户", "知道了");
        // 时间选择
        mTimeStyle = new SimpleDateFormat("yyyy-MM");
        String time = mTimeStyle.format(new Date());
        mBinding.tvTime.setText(time.split("-")[0] + "年" + time.split("-")[1] + "月");
        Calendar end = Calendar.getInstance();
        end.add(Calendar.YEAR, -1);
        mTimePicker = new TimePickerBuilder(this, (date, z) -> {
            String selTime = mTimeStyle.format(date);
            mBinding.tvTime.setText(selTime.split("-")[0] + "年" + selTime.split("-")[1] + "月");
            mModel.getPayFlowStatistics(this, selTime);
        }).setType(new boolean[]{true, true, false, false, false, false})
                .setTitleText("选择日期")
                .setTitleColor(Utils.getColor(R.color.color_969696))
                .setTitleSize(15)
                .setDate(Calendar.getInstance())
                .setRangDate(end, Calendar.getInstance())
                .build();
        // 计算收入支出比例
        scale(0);
        if (mIsUser) {
            mModel.getBusinessInfoByUser(this);
        } else {
            mModel.getBusinessInfoByCompany(this);
        }
        mModel.getProcess(this);
        mModel.getPayFlowStatistics(this, time);
        mModel.statisticsNumberAndMoney(this);
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    private void scale(int type) {
        switch (type) {
            case 0:
                mBinding.llType0.setVisibility(View.VISIBLE);
                mBinding.llType1.setVisibility(View.GONE);
                mBinding.llType2.setVisibility(View.GONE);
                break;
            case 1:
                mBinding.llType0.setVisibility(View.GONE);
                mBinding.llType1.setVisibility(View.VISIBLE);
                mBinding.llType2.setVisibility(View.GONE);
                mBinding.dvRatio.setBackground(getResources().getDrawable(mPayeeAmount > mPayAmount ? R.drawable.corner2_income_bg : R.drawable.corner2_expend_bg));
                break;
            case 2:
                mBinding.llType0.setVisibility(View.GONE);
                mBinding.llType1.setVisibility(View.GONE);
                mBinding.llType2.setVisibility(View.VISIBLE);
                break;
        }
        float incomeMoney = mPayeeAmount;
        float expendMoney = mPayAmount;
        float v = Math.abs((incomeMoney / expendMoney) >= 30 ? 30 : (incomeMoney / expendMoney));
        float scaleIncomeMoney = incomeMoney >= expendMoney && v < 1 ? v : 1;
        float scaleExpendMoney = incomeMoney > expendMoney && v < 1 ? 1 : v;
        LinearLayout.LayoutParams lp1 = (LinearLayout.LayoutParams) mBinding.dvIncomeMoney.getLayoutParams();
        lp1.weight = scaleIncomeMoney;
        mBinding.dvIncomeMoney.setLayoutParams(lp1);
        LinearLayout.LayoutParams lp2 = (LinearLayout.LayoutParams) mBinding.dvExpendMoney.getLayoutParams();
        lp2.weight = scaleExpendMoney;
        mBinding.dvExpendMoney.setLayoutParams(lp2);
    }

    public void initObserve() {
        mModel.mBean.observe(this, bean -> {
            mMoney = Utils.getDecimalFormat(bean.money);
            mBinding.tvNumber2.setText(isOn ? "￥" + mMoney : "*****");
        });
        mModel.mCapitalEntity.observe(this, capitalEntity -> getProcess(capitalEntity));
        mModel.mUserBusinessInfoByCompanyEntity.observe(this, businessInfoByCompanyEntity -> getBusinessInfoByCompany(businessInfoByCompanyEntity));
        mModel.mBusinessInfoByCompanyEntity.observe(this, businessInfoByCompanyEntity -> getBusinessInfoByCompany(businessInfoByCompanyEntity));
        mModel.mPayFlowStatisticsEntity.observe(this, capitalEntity -> getPayFlowStatistics(capitalEntity));
    }

    public void initListener() {
        mBinding.ivAccount.setOnClickListener(v -> getStart());
        mBinding.llAccount.setOnClickListener(v -> getStart());
        // 去开通
        mTipNoOpen.mTvSure.setOnClickListener(v -> {
                    mTipNoOpen.dismiss();
                    OpenAccountFirstActivity.start(this, mIsUser);
                }
        );
        mBinding.ivBack.setOnClickListener(v -> {
            finish();
        });
        // 订单
        mBinding.llBtn.setOnClickListener(v -> BusinessManagementActivity.start(CapitalActivity.this, 1));
        mBinding.tvTip.setOnClickListener(v -> mTip.show());
        mAdapter.setOnItemClickListener((adapter, view, position) ->
        {
            switch (position) {
                case 6:
                    // 已付账单
                    BusinessManagementActivity.start(this, 2);
                    break;
                case 7:
                    // 已收账单
                    BusinessManagementActivity.start(this, 4);
                    break;
                case 8:
                    // 退款列表
                    if (verification()) return;
                    ReimburseActivity.start(this);
                    break;
                case 0:
                    if (verification()) return;
                    if (mProcess == 2) {
                        mTipBind.show();
                        return;
                    }
                    WithdrawalBalanceActivity.start(this, mIsUser);
                    break;
                case 1:
                    // 账务流水
                    FinanceFlowAndCostQueryActivity.start(this, mIsUser, 0);
                    break;
                case 2:
                    // 银行卡
                    bindBank();
                    break;
                case 3:
                    // 余额充值
                    if (verification()) return;
                    PayActivity.start(this, true, mIsUser);
                    break;
                case 4:
                    // 账户明细
                    getStart();
                    break;
                case 5:
                    // 费用查询
                    //  FinanceFlowAndCostQueryActivity.start(this, mIsUser, 1);
                    if (mIsUser) {
                        FinanceFlowAndCostQueryActivity.start(this, true, 1);
                    } else {
                        if (verification()) return;
                        TransferAccountsActivity.start(this);
                    }
                    break;
            }
        });
        mTipBind.mTvSure.setOnClickListener(v ->
                {
                    mTipBind.dismiss();
                    bindBank();
                }
        );
        mBinding.tvBtn.setOnClickListener(v -> {
            if (mBinding.tvBtn.getText().toString().contains("立即开通")) {
                OpenAccountFirstActivity.start(this, mIsUser);
            } else if (mBinding.tvBtn.getText().toString().contains("重新开通")) {
                OpenAccountFirstActivity.start(this, mIsUser);
            } else if (mBinding.tvBtn.getText().toString().contains("立即绑卡")) {
                bindBank();
            } else {
                MToast.showToast(Utils.getContext(), "银行卡");
            }
        });
        mBinding.tvTime.setOnClickListener(v -> mTimePicker.show());
        mBinding.ivEye.setOnClickListener(v -> {
            try {
                isOn = !isOn;
                mBinding.ivEye.setImageResource(isOn ? R.mipmap.eye_on : R.mipmap.eye_off);
                mBinding.tvBalanceMoney.setText(isOn ? mBalance : "*****");
                mBinding.tvRetentionMoney.setText(isOn ? Utils.getDecimalFormat(Float.parseFloat(mAssBal)) : "*****");
                mBinding.tvIncomeMoney.setText(isOn ? mPayeeAmount == 0 ? "0.00" : mPayeeAmount + "" : "*****");
                mBinding.tvExpendMoney.setText(isOn ? mPayAmount == 0 ? "0.00" : mPayAmount + "" : "*****");
                mBinding.tvNumber2.setText(isOn ? "￥" + mMoney : "*****");
            } catch (Exception ignored) {
            }
        });
    }


    private void getStart() {
        if (verification()) return;
        AccountActivity.start(this);
    }

    private boolean verification() {
        if (mProcess == 0 || mProcess == 3 || mProcess == 1) {
            mTipNoOpen.initStr("温馨提示",
                    mProcess == 1 ? ("企业钱包开通审核中\n通过后可使用此功能") : (mIsUser ? "开通个人钱包后\n" : "开通企业钱包后\n") +
                            "可使用此功能", (mProcess == 1 || mProcess == 2) ? null : "前往开通", "知道了");
            mTipNoOpen.show();
            return true;
        }
        return false;
    }

    private void bindBank() {
        if (mIsUser) {
            PersonBankCardsActivity.start(this);
        } else {
            CompanyBankCardsActivity.start(this, mProcess);
        }
    }


    @SuppressLint("UseCompatLoadingForDrawables")
    public void getProcess(CapitalEntity data) {
        //步骤（审核状态 0-初始、1-待审批、2-审批通过、3-审批不通过 4-绑定了银行卡)
        mProcess = data.process;
        mBinding.llProcess.setVisibility(data.process == 4 ? View.GONE : View.VISIBLE);
        if (data.process == 0)
            return;
        mBinding.tvTip3.setText(data.msg);
        mBinding.tvTip1.setText(data.process == 1 ? "资金账户开通审核中" : data.process == 3 ? "开通失败" : "绑定银行卡");
        mBinding.tvTip2.setText(data.process == 1 ? "开通后，销售订单可使用在线收款" : data.process == 3 ? "失败原因：资质文件名称不正确或者是\n多余文件" : "绑定银行卡可进行资金提现");
        mBinding.tvTip2.setVisibility(data.process == 3 ? View.GONE : View.VISIBLE);
        mBinding.llFail.setVisibility(data.process == 3 ? View.VISIBLE : View.GONE);
        mBinding.tvBtn.setText(data.process == 3 ? "重新开通" : data.process == 2 ? "立即绑卡" : "立即开通");
        mBinding.llBg.setBackground(Utils.getResources().getDrawable(data.process == 1 ? R.mipmap.audit_bg : data.process == 3 ? R.mipmap.fail_bg : R.mipmap.opened_bg));
        mBinding.tvBtn.setVisibility(data.process == 1 ? View.INVISIBLE : View.VISIBLE);
        mBinding.tvTip1.setTextColor(Utils.getColor(data.process == 1 ? R.color.c_FF4B10 : data.process == 2 ? R.color.c_5792FD : R.color.c_FF2928));
        mBinding.tvTip2.setTextColor(Utils.getColor(data.process == 1 ? R.color.c_FF4B10 : data.process == 2 ? R.color.c_5792FD : R.color.c_FF2928));
    }

    public void getBusinessInfoByCompany(BusinessInfoByCompanyEntity data) {
        mBalance = data.balance == 0 ? "0.00" : Utils.getDecimalFormat(data.balance) + "";
        mAssBal = data.assBal == 0 ? "0.00" : data.assBal + "";
        mBinding.tvBalanceMoney.setText(isOn ? mBalance : "*****");
        mBinding.tvRetentionMoney.setText(isOn ? Utils.getDecimalFormat(Float.parseFloat(mAssBal)) : "*****");
        mBinding.tvNumber.setVisibility(data.orderCount == 0 ? View.GONE : View.VISIBLE);
        mBinding.tvNumber2.setVisibility(data.orderCount == 0 ? View.GONE : View.VISIBLE);
        String numberStr = "共" + data.orderCount + "笔,合计";
        mBinding.tvNumber.setText(numberStr);
    }

    public void getPayFlowStatistics(PayFlowStatisticsEntity data) {
        mPayeeAmount = data.payeeAmount;
        mPayAmount = data.payAmount;
        mBinding.tvIncomeMoney.setText(isOn ? data.payeeAmount == 0 ? "0.00" : data.payeeAmount + "" : "*****");
        mBinding.tvExpendMoney.setText(isOn ? data.payAmount == 0 ? "0.00" : data.payAmount + "" : "*****");
        int type = (mPayeeAmount == 0 && mPayAmount == 0) ? 0 : (mPayeeAmount != 0 && mPayAmount != 0) ? 2 : 1;
        scale(type);
    }


    @Subscribe
    public void getCode(ZMessageEvent event) {
        switch (event.code) {
            case Constants
                    .EVENT_REFRESH:
                if (mIsUser) {
                    mModel.getBusinessInfoByUser(this);
                } else {
                    mModel.getBusinessInfoByCompany(this);
                }
                mModel.statisticsNumberAndMoney(this);
                mModel.getProcess(this);
                break;
            case Constants
                    .EVENT_HIDE_MAIN:
                finish();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Utils.sendMsg(Constants.EVENT_REFRESH_DATA,null);
        EventBus.getDefault().unregister(this);
    }
}